package thread;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description: 手写计时器
 * User: 王圆豪
 * Date: 2025-05-05
 * Time: 16:16
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    //要执行的任务
    private Runnable task;
    //要等待的时间
    private long time;

    //构造方法
    public MyTimerTask(Runnable task, long time){
        this.task = task;
        this.time = time;
    }

    //重写compareTo方法
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }

    public long getTime() {
        return time;
    }

    public Runnable getTask() {
        return task;
    }
}

class MyTimer{
    //用优先级队列储存MyTimerTask
    private static PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    private Object locker = new Object();

    //schedule方法
    public void schedule(Runnable task, long time) {
        synchronized(locker){
            MyTimerTask t = new MyTimerTask(task,time + System.currentTimeMillis());
            queue.add(t);
            locker.notify();
        }
    }

    //构造方法
    public MyTimer(){
        Thread t = new Thread(()->{
            while (true) {
                synchronized (locker) {
                    while (queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask task = queue.peek();
                    if (System.currentTimeMillis() < task.getTime()){
                        try {
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        task.getTask().run();
                        queue.poll();
                    }
                }
            }
        });
        t.start();
    }
}

public class Demo33 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
    }
}
